package com.freeter.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpConnectionPoolUtil {
    private static Log logger = LogFactory.getLog(HttpConnectionPoolUtil.class);

    public static final String UTF8 = "UTF-8";
    public static volatile boolean isClosed = false;

    public static final int maxTotalPool = 150;
    public static final int MAX_TIMEOUT = 5000;
    public static final int RequestTimeout = 2000;

    private static RequestConfig requestConfig;
    private static HttpClientBuilder httpClientBuilder;
    private static PoolingHttpClientConnectionManager poolConnManager;

    // 相当于线程锁,用于线程安全
    private final static Object syncLock = new Object();

    static {
        // 设置连接池
        poolConnManager = new PoolingHttpClientConnectionManager();
        //设置连接池大小
        poolConnManager.setMaxTotal(maxTotalPool);
        poolConnManager.setDefaultMaxPerRoute(maxTotalPool);

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(RequestTimeout);
        // 在提交请求之前 测试连接是否可用
        //configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
        httpClientBuilder = HttpClients.custom().setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig);
        logger.info(">>>>>>>>>>> PoolingHttpClientConnectionManager初始化成功 >>>>>>>>>>>");
    }

    /**
     * 获取HttpClient客户端
     *
     * @return httpClient
     */
    public static CloseableHttpClient getClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
        if (null == httpClient) {
            httpClient = HttpClients.createDefault();
        }

        return httpClient;
    }

    /**
     * 从http连接池里获取客户端实例
     *
     * @return httpClient
     */
    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = httpClientBuilder.build();
        if (null == httpClient) {
            synchronized (syncLock) {
                if (null == httpClient) {
                    logger.info("---------HttpClients.createDefault()---------");
                    httpClient = HttpClients.createDefault();
                }
            }
        }

        return httpClient;
    }

    /**
     * 关闭连接池资源
     */
    public static void closePool() {
        if (!isClosed) {
            isClosed = true;
            poolConnManager.close();
        }
    }

}